package geektime.spring.springbucks.customerservice;

import java.security.KeyStore;
import java.time.Duration;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.OkHttpClient.Builder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.Banner.Mode;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.Resource;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

@Slf4j
@SpringBootApplication
public class CustomerServiceApplication {

  @Value("${security.key-store}")
  private Resource keyStore;
  @Value("${security.key-pass}")
  private String keyPass;

  public static void main(String[] args) {
//		SpringApplication.run(CustomerServiceApplication.class, args);
    new SpringApplicationBuilder()
        .sources(CustomerServiceApplication.class)
        .bannerMode(Mode.OFF)
        .web(WebApplicationType.NONE)
        .run(args);

  }

  @Bean
  public OkHttp3ClientHttpRequestFactory requestFactory() {
    OkHttpClient okHttpClient = null;
    try {
      KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType());
      store.load(this.keyStore.getInputStream(), keyPass.toCharArray());
      TrustManagerFactory tmf = TrustManagerFactory
          .getInstance(TrustManagerFactory.getDefaultAlgorithm());
      tmf.init(store);
      SSLContext sslContext = SSLContext.getInstance("TLS");
      sslContext.init(null, tmf.getTrustManagers(), null);
      okHttpClient = new Builder().sslSocketFactory(sslContext.getSocketFactory(),
          (X509TrustManager) tmf.getTrustManagers()[0])
          .hostnameVerifier((hostname, session) -> true)
          .build();
    } catch (Exception e) {
      log.error("Exception occurred while creating SSLContext.", e);
    }

    OkHttp3ClientHttpRequestFactory requestFactory = new OkHttp3ClientHttpRequestFactory(
        okHttpClient);

    return requestFactory;
  }

  @Bean
  public RestTemplate restTemplate(RestTemplateBuilder builder) {
    return builder.setConnectTimeout(Duration.ofMillis(1000))
        .setReadTimeout(Duration.ofMillis(5000))
        .requestFactory(this::requestFactory)
        .build();
  }

}
